package com.guigu.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.guigu.pojo.Merchant;
import com.guigu.service.MerchantService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.guigu.pojo.Consumer;
import com.guigu.pojo.Merchant;
import com.guigu.pojo.UserAddress;
import com.guigu.service.ConsumerService;
import com.guigu.service.MerchantService;
import com.guigu.utils.FileUploadUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 商户表 前端控制器
 * </p>
 *
 * @author Mr.Zhang
 * @since 2025-03-12
 */
@CrossOrigin
@RestController
@RequestMapping("/merchant")
public class MerchantController {
    @Autowired
    private MerchantService merchantService;

    @GetMapping("/page")
    public Map<String, Object> getMerchantPage(@RequestParam(defaultValue = "1") Integer currentPage,
                                               @RequestParam(defaultValue = "10") Integer pageSize,
                                               @RequestParam(required = false) String shopName,
                                               @RequestParam(required = false) String shopType,
                                               @RequestParam(required = false) String startDate,
                                               @RequestParam(required = false) String endDate) {
        List<Merchant> merchantList = merchantService.getMerchantWithNickname(shopName, shopType, startDate, endDate);
        Page<Merchant> page = new Page<>(currentPage, pageSize);
        int startIndex = (int) ((currentPage - 1) * pageSize);
        int endIndex = Math.min(startIndex + (int) pageSize, merchantList.size());
        page.setRecords(merchantList.subList(startIndex, endIndex));
        page.setTotal(merchantList.size());

        Map<String, Object> result = new HashMap<>();
        result.put("total", page.getTotal());
        result.put("rows", page.getRecords());
        return result;
    }

    @PutMapping("/update")
    public boolean updateMerchant(@RequestBody Merchant merchant) {
        return merchantService.updateMerchant(merchant);
    }

    @DeleteMapping("/delete/{merchantId}")
    public boolean deleteMerchant(@PathVariable Integer merchantId) {
        return merchantService.deleteMerchant(merchantId);
    }

    @Autowired
    private ConsumerService consumerService;

    @PostMapping("/getAllMerchantByAddress")
    @ResponseBody
    public List<Merchant> getAllMerchant(@RequestBody Consumer user) {
        QueryWrapper<Merchant> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("address", user.getUserAddress().get(0).getAddress());
        queryWrapper.eq("on_off","1");
        queryWrapper.eq("status","C001-1");
        queryWrapper.eq("check_tag","S001-3");
        List<Merchant> list = merchantService.list(queryWrapper);
        return list;
    }

    @GetMapping("/getMerchantByConsumerId")
    @ResponseBody
    public Merchant getMerchantByConsumerId(Integer consumerId) {
        QueryWrapper<Merchant> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("consumer_id", consumerId);
        Merchant merchant = merchantService.getOne(queryWrapper);
        return merchant;
    }

    @PostMapping("/saveMerchant")
    @ResponseBody
    @Transactional
    public Merchant updateUser(@RequestParam("files") MultipartFile[] files, Merchant merchant, HttpServletRequest req) {
        // 创建用户对象并设置用户名和密码
        System.out.println("merchant:"+merchant);

        // 设置文件上传的基础路径，并根据日期生成子路径
        String basePathStr = "C:\\Users\\Mr.Zhang\\document\\upload";
        String subPath = FileUploadUtils.makeUploadDirectoryByDate();
        basePathStr += subPath; // 文件上传的地址

        // 检查基础路径是否存在，如果不存在则创建
        File basePath = new File(basePathStr);
        if (!basePath.exists()) {
            basePath.mkdirs();
        }

        try {
            // 遍历上传的文件数组，重命名文件并保存到指定路径
            for (MultipartFile f : files) {
                String newFileName = FileUploadUtils.rename(f.getOriginalFilename());
                f.transferTo(new File(basePath, newFileName));
                merchant.setShopImg(subPath + newFileName);// 设置用户头像路径
            }
        } catch (Exception e) {
            throw new RuntimeException(e); // 捕获并抛出异常
        }
        merchant.setOnOff(1);
        merchant.setCreateDate(new Date());
        // 保存用户信息并返回结果
        boolean b = merchantService.saveOrUpdate(merchant);
        Consumer consumer = consumerService.getById(merchant.getConsumerId());
        consumer.setMerchantTag("S001-2");
        consumerService.updateById(consumer);

        return merchant;
    }



    @GetMapping("/page2")
    public Map<String, Object> getMerchantPage2(@RequestParam(defaultValue = "1") Integer currentPage,
                                                @RequestParam(defaultValue = "10") Integer pageSize,
                                                @RequestParam(required = false) String shopName,
                                                @RequestParam(required = false) String shopType,
                                                @RequestParam(required = false) String startDate,
                                                @RequestParam(required = false) String endDate,
                                                @RequestParam(required = false) String checkTag) {
        Page<Merchant> page = new Page<>(currentPage, pageSize);
        IPage<Merchant> merchantPage = merchantService.getMerchantPage2(page, shopName, shopType, startDate, endDate, checkTag);
        Map<String, Object> result = new HashMap<>();
        result.put("total", merchantPage.getTotal());
        result.put("rows", merchantPage.getRecords());
        return result;
    }

    @GetMapping("/{id}")
    @ResponseBody
    public Merchant getById(@PathVariable Integer id) {
        Merchant merchant = merchantService.selectMerchantWithNicknameById(id);
        return merchant;
    }

    @PutMapping("/review")
    @ResponseBody
    public Boolean review(@RequestBody Merchant merchant) {
        return merchantService.review(merchant);
    }
}
